<template>
  <div class="container app-container">
    <div class="form">
      <el-form :model="form" :rules="rules" ref="form" label-width="150px">
        <div
          class="title"
          style="
            margin: 20px 0 20px 0;
            height: 20px;
            line-height: 20px;
            border-left: 1px solid #ccc;
            text-indent: 15px;
          "
        >
          求职信息
        </div>
        <el-row>
          <el-col :span="8">
            <el-form-item label="求职船员" prop="crewId">
              <el-select v-model="form.crewId" filterable placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in crewList"
                  :key="item.id"
                  :label="item.crewName"
                  :value="item.id"
                  @change="handleCrewInfo"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="求职标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名" prop="name">
              <el-input disabled v-model="form.name" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="年龄" prop="age">
              <el-input placeholder="请输入" v-model="form.age">
                <template slot="append">岁</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sexStr">
                <el-radio value="0" label="男"></el-radio>
                <el-radio value="1" label="女"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="所在城市" prop="cityCode">
              <el-cascader
                style="width: 100%"
                clearable
                filterable
                v-model="form.cityCode"
                :options="options"
                @change="handleCityChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="学历" prop="education">
              <el-select
                v-model="form.education"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in educationList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.info"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工作经验" prop="age">
              <el-input placeholder="请输入" v-model="form.age">
                <template slot="append">年</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="证书资格类别" prop="credentialsType">
              <el-select
                v-model="form.credentialsType"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in credentialsTypeList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.info"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="证书等级" prop="credentialsLevel">
              <el-select
                v-model="form.credentialsLevel"
                filterable
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in credentialsLevelList"
                  :key="item.code"
                  :label="item.info"
                  :value="item.info"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="截止日期" prop="endDate" required>
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="form.endDate"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" :rows="5" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="footer">
      <el-button type="primary" class="submit-btn" @click="submitForm">
        {{ isEdit ? '确定保存' : '确定新增' }}
      </el-button>
    </div>
  </div>
</template>

<script>
// 导入接口方法
import {
  educationEnum,
  getRegionTree,
  credentialsTypeEnum,
  credentialsLevelEnum,
} from '@/api/common';
import { getDetail, add, update } from '@/api/orders/orderStaff';
import { getCrewTreeList } from '@/api/crew';

export default {
  name: 'OrderStaffSave',
  data() {
    return {
      // 标题
      title: '',
      // 初始化 id 为 null
      id: null,
      // 初始化 isEdit 为 false
      isEdit: false,
      // 表单参数
      form: {
        id: null, // id
        crewId: null, // 船员id
        title: null, // 订单标题
        age: null, // 年龄
        sex: null, // 性别
        province: null, // 省份
        city: null, // 城市
        cityCode: null, // 所在城市
        education: null, // 学历
        experience: null, // 工作经验
        credentialsType: null, // 证书类别
        credentialsLevel: null, // 证书等级
        endDate: null, // 截止日期
        remark: null, // 备注
      },
      // 船员下拉列表
      crewList: [],
      // 学历下拉列表
      educationList: [],
      // 证书类别下拉列表
      credentialsTypeList: [],
      // 证书等级下拉列表
      credentialsLevelList: [],
      // 省市区数据
      options: [],
      // 表单校验
      rules: {
        crewId: [{ required: true, message: '请选择船员', trigger: 'blur' }],
        title: [{ required: true, message: '请输入订单标题', trigger: 'blur' }],
        age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
        cityCode: [{ required: true, message: '请选择所在城市', trigger: 'blur' }],
        education: [{ required: true, message: '请选择学历', trigger: 'blur' }],
        experience: [{ required: true, message: '请输入工作经验', trigger: 'blur' }],
        credentialsType: [{ required: true, message: '请选择证书类别', trigger: 'blur' }],
        credentialsLevel: [{ required: true, message: '请选择证书等级', trigger: 'blur' }],
        endDate: [{ required: true, message: '请选择截止日期', trigger: 'blur' }],
      },
    };
  },
  created() {
    // 通过 $route.params 获取路由参数
    this.id = this.$route.query.id ? this.$route.query.id : null;
    // 判断是否存在 id 参数
    this.isEdit = !!this.id;
    if (this.isEdit) {
      this.getDataById(this.id);
    }
  },
  watch: {
    '$route.query.id': {
      handler(newId) {
        this.id = newId || null;
        this.isEdit = !!newId;
        if (this.isEdit) {
          this.getDataById(this.id);
        }
      },
      immediate: true, // 在组件创建时立刻执行一次
    },
  },
  mounted() {
    this.getRegionTree();
    this.getCrewList();
    this.getEducationLevelList();
    this.getCredentialsLevelList();
    this.getCredentialsTypeList();
  },
  methods: {
    // 获取船员下拉列表
    getCrewList() {
      getCrewTreeList().then((res) => {
        this.crewList = res.data;
      });
    },

    // 获取学历下拉列表
    getEducationLevelList() {
      educationEnum().then((res) => {
        this.educationList = res.data;
      });
    },
    // 获取证书类别下拉列表
    getCredentialsTypeList() {
      credentialsTypeEnum().then((res) => {
        this.credentialsTypeList = res.data;
      });
    },
    getCredentialsLevelList() {
      credentialsLevelEnum().then((res) => {
        this.credentialsLevelList = res.data;
      });
    },

    /** 获取form表单数据 */
    async getDataById(id) {
      getDetail(id).then((res) => {
        this.form = res.data;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.id != null) {
            this.$confirm('确定修改当前内容', '确定保存', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用修改接口
                this.handleUpdate();
              })
              .catch(() => {});
          } else {
            this.$confirm('确定新增', '确定新增', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            })
              .then(() => {
                // 调用新增接口
                this.handleAdd();
              })
              .catch(() => {});
          }
        }
      });
    },

    /** 新增 */
    handleAdd() {
      let saveData = {
        ...this.form,
      };
      this.$modal.loading('正在保存...');

      add(saveData)
        .then((res) => {
          if (res.code === 200) {
            this.$modal.msgSuccess('新增成功');
            this.close();
          } else {
            this.$message.error(res.message);
          }
          this.$modal.closeLoading();
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },

    /** 更新 */
    handleUpdate() {
      let saveData = {
        ...this.form,
      };
      saveData.id = this.id;
      this.$modal.loading('正在保存...');

      update(saveData)
        .then((res) => {
          if (res.code === 200) {
            this.$modal.msgSuccess('保存成功');
            this.close();
          }
          this.$modal.closeLoading();
        })
        .catch(() => {
          this.$modal.closeLoading();
        });
    },
    handleCrewInfo(value) {
      this.form.crewId = value.id;
      this.form.crewName = value.name;
      this.form.age = value.age;
      this.form.sexStr = value.sexStr;
      this.form.province = value.province;
      this.form.city = value.city;
      this.form.education = value.education;
      this.form.experience = value.experience;
      this.form.credentialsType = value.credentialsType;
      this.form.credentialsLevel = value.credentialsLevel;
    },
    async getRegionTree() {
      const res = await getRegionTree(2);
      // 将原始数据转换为 el-cascader 需要的格式
      this.options = this.formatOptions(res.data);
    },
    formatOptions(data) {
      // 将原始数据转化为 el-cascader 组件所需的嵌套结构
      return data.map((item) => ({
        value: item.code, // 或者根据实际情况可能是 item.id
        label: item.name,
        ...(item.child && { children: this.formatOptions(item.child) }), // 使用展开运算符(...)仅在item.child存在时添加children属性
      }));
    },
    handleCityChange(value) {
      const selectedLabels = value.map((item) => this.getLabelByValue(item, this.options));
      this.form.province = selectedLabels[0];
      this.form.city = selectedLabels[1];
    },
    getLabelByValue(value, options) {
      for (const option of options) {
        if (option.value === value) {
          return option.label;
        }
        if (option.children) {
          const childLabel = this.getLabelByValue(value, option.children);
          if (childLabel) {
            return childLabel;
          }
        }
      }
      return '';
    },

    /** 关闭按钮 */
    close() {
      // 跳转地址 和 携带参数
      const obj = {
        path: '/orders/staff/list/index',
      };
      this.$tab.closeOpenPage(obj).then(() => {
        this.$tab.refreshPage(obj);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
}

.submit-btn {
  position: fixed;
  bottom: 10px;
  left: 50%;
}
</style>
